use aes_gcm_siv::{
    aead::{Aead, KeyInit, OsRng},
    Aes256GcmSiv, Nonce // Or `Aes128GcmSiv`
};
use aes_gcm_siv::aead::generic_array::GenericArray;
use sha3::{Digest, Sha3_256};
fn encrypt(key : String, nonce: String, plaintext : String ) -> Vec<u8> {
    let mut hasher = Sha3_256::new();
    hasher.update(key.as_bytes());
    let result = hasher.finalize();

    let key =GenericArray::from_slice(result.as_slice());
    println!("key.len: {}", key.len());

    let cipher = Aes256GcmSiv::new(&key);
    let nonce = Nonce::from_slice(&nonce.as_bytes());
    let ciphertext = cipher.encrypt(nonce, plaintext.as_bytes()).unwrap();
    ciphertext
}

fn decrypt(key : String, nonce: String, ciphertext : Vec<u8>) -> String {
    let mut hasher = Sha3_256::new();
    hasher.update(key.as_bytes());
    let result = hasher.finalize();

    let key =GenericArray::from_slice(result.as_slice());

    let cipher = Aes256GcmSiv::new(&key);
    let nonce = Nonce::from_slice(&nonce.as_bytes());
    let plaintext = cipher.decrypt(nonce, ciphertext.as_ref()).unwrap();

    String::from_utf8(plaintext).unwrap()
}

fn main() {
    let key = Aes256GcmSiv::generate_key(&mut OsRng);
    let cipher = Aes256GcmSiv::new(&key);
    let nonce = Nonce::from_slice(b"unique nonce"); // 96-bits; unique per message
    let ciphertext = cipher.encrypt(nonce, b"plaintext message".as_ref()).unwrap();
    let plaintext = cipher.decrypt(nonce, ciphertext.as_ref()).unwrap();
    println!("{:?}", String::from_utf8(plaintext).unwrap());


    let key = String::from("helloworld");
    let nonce = String::from("fenghuolinsh");
    let plaintext = String::from("haolifeng is a big persion");

    let encrypted = encrypt(key.clone(), nonce.clone(), plaintext);
    println!("{:?}", encrypted);
    let decrypted = decrypt(key, nonce, encrypted);
    println!("{:?}", decrypted)


}